package com.gouwudai.gobbs.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;

import com.gouwudai.gobbs.common.IPageList;
import com.gouwudai.gobbs.dao.IMasterGradeDAO;
import com.gouwudai.gobbs.pojo.TbbsMasterGrade;
import com.litt.core.common.Utility;
import com.litt.core.exception.BusiException;
import com.litt.core.exception.DBException;

public class MasterGradeDAOImpl extends BaseDAOImpl implements IMasterGradeDAO 
{
	private static final Logger logger = Logger.getLogger(MasterGradeDAOImpl.class);	
	private static final String BUSI_NAME = "管理员等级信息";
	
	public void save(TbbsMasterGrade tbbsMasterGrade) throws BusiException
	{
    	if(this.loadByName(tbbsMasterGrade.getGradeName())!=null)
    		throw new DBException("该管理员等级名称已存在！");	
		super.saveObject(tbbsMasterGrade);		
	}
	
	public TbbsMasterGrade load(Integer id)
	{
		return (TbbsMasterGrade)super.loadObject(TbbsMasterGrade.class, id);
	} 
	
	/**
	 * 根据用户名获得用户信息
	 * @param gradeName
	 * @return
	 */
	public TbbsMasterGrade loadByName(String gradeName) 
	{		
		String hql = "from TbbsMasterGrade where gradeName='"+gradeName+"'";	
		TbbsMasterGrade masterGradeInfo = (TbbsMasterGrade)super.uniqueResultHql(hql);
		
		return masterGradeInfo;
	}	
    
    public void update(TbbsMasterGrade tbbsMasterGrade) throws BusiException
    {
    	//验证    	
    	String vhql = "from TbbsMasterGrade where gradeName='"+tbbsMasterGrade.getGradeName()+"' and mgId<>"+tbbsMasterGrade.getMgId();	
    	TbbsMasterGrade masterGradeInfo = (TbbsMasterGrade)super.uniqueResultHql(vhql);
		if(masterGradeInfo!=null)
			throw new DBException("该管理员等级名称已存在！");	
		//验证结束
    	StringBuilder hql = new StringBuilder();
        hql.append("update TbbsMasterGrade set gradeName=?"); 
        hql.append(", remark=?");
        hql.append(" where mgId=?");
        super.updateObject(hql.toString(), new Object[]{
        	tbbsMasterGrade.getGradeName(),
        	tbbsMasterGrade.getRemark(),
        	tbbsMasterGrade.getMgId()});

    }
    
    public void delete(Integer mgId) throws BusiException
    {
        //1.验证该等级下是否还有用户存在
    	String hql = "select count(*) from TbbsMaster where mgId="+mgId;
    	
    	int count = super.listHqlCount(hql);
    	if(count>0)
    		throw new BusiException("该等级下还有用户存在，不能删除");
    	//1.结束-----
    	super.deleteObject(TbbsMasterGrade.class.getName(),"mgId",mgId);
    }
    
    public List listAll()
    { 
    	return super.listAll(TbbsMasterGrade.class);
    }
    

    public IPageList listPage(int pageIndex,int pageSize,String sort)
    {       
    	StringBuilder listSql = new StringBuilder("SELECT * FROM TbbsMasterGrade ");
        if(!Utility.isEmpty(sort))
            listSql.append(sort);
    	return super.listSqlPage(listSql.toString(),pageIndex,pageSize);
    }
    
}
